package com.example.learn_mybatis.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.learn_mybatis.mapper.*;
import com.example.learn_mybatis.pojo.*;
import com.example.learn_mybatis.service.IUsersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author chen
 * @since 2025-07-11
 */
@Slf4j
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements IUsersService {

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private RolePermissionsMapper rolePermissionsMapper;

    @Autowired
    private PermissionsMapper permissionsMapper;

    @Override
    public Pager getRolesByUserId(Integer id, Integer page, Integer size) {
        Page<Roles> pages = new Page<>(page, size);
        Pager pager =  new Pager();

        IPage<Roles> rolesIPage = this.baseMapper.selectRolesPage(pages, id);

        pager.setTotal(rolesIPage.getPages());
        pager.setList(Collections.singletonList(rolesIPage.getRecords()));

        return pager;

    }

    /**
     * 获取所有用户的权限
     * @return
     */
    @Override
    public Map<String, List<Permissions>> getAllPermissions(){
        HashMap<String, List<Permissions>> map = new HashMap<>();
        List<Users> users = this.baseMapper.selectList(null);
        log.info("users {}", users);

        users.forEach(user->{
            map.put(String.valueOf(user.getId()), this.getAllPermission(Math.toIntExact(user.getId())));
        });
        return map;
    }

    @Override
    public List<Permissions> getAllPermission(Integer id) {

        // 获取关联的roleId
        List<UserRole> roles = this.getRolesByUserId(id);

        // 获取对应role的permission
        List<RolePermissions> rolePermissions = this.getPermissionsByRoleId(roles);

        // 获取权限
        List<Permissions> permissions = this.getPermissionsById(rolePermissions);


        return permissions;
    }

    @Override
    public Users getUser(Users user) {
        LambdaQueryWrapper<Users> userWrapper = new LambdaQueryWrapper<>();
        userWrapper.eq(Users::getPassword, user.getPassword()).eq(Users::getUsername, user.getUsername());
        return this.baseMapper.selectOne(userWrapper);
    }

    public List<Permissions> getPermissionsById(List<RolePermissions> rolePermissions) {
        if(rolePermissions==null||rolePermissions.size()==0){
            return new ArrayList<>();
        }
        ArrayList<Integer> permissionIds = new ArrayList<>();
        rolePermissions.forEach(rolePermission -> {
            permissionIds.add(rolePermission.getPermissionId());
        });
        LambdaQueryWrapper<Permissions> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(Permissions::getId, permissionIds);
        return permissionsMapper.selectList(wrapper);
    }

    /**
     * 获取对应role的permission
     * @param roles
     * @return
     */
    public List<RolePermissions> getPermissionsByRoleId(List<UserRole> roles) {
        if(roles == null || roles.size() == 0){
            return new ArrayList<>();
        }
        ArrayList<Integer> roleIds = new ArrayList<>();
        roles.forEach(role -> {
            roleIds.add(Math.toIntExact(role.getRoleId()));
        });

        LambdaQueryWrapper<RolePermissions> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(RolePermissions::getRoleId, roleIds);
        return rolePermissionsMapper.selectList(wrapper);
    }

    /**
     * 获取关联的roleId
     * @param id
     * @return
     */
    public List<UserRole> getRolesByUserId(Integer id) {
        LambdaQueryWrapper<UserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserRole::getUserId, id);
        return userRoleMapper.selectList(wrapper);
    }


    /**
     * 获取分页的用户信息
     * @param size
     * @param p
     * @return
     */
    public Pager getAllUser(Integer size, Integer p) {
        Pager pager = new Pager();

        Page<Users> page = new Page<>(p, size);
        Page<Users> usersPage = this.page(page);

        pager.setTotal(usersPage.getPages());
        pager.setList(Collections.singletonList(usersPage.getRecords()));
        return pager;
    }
}
